import { Injectable } from '@nestjs/common';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { DataSource } from 'typeorm';
import { RouteDto } from './dto/route.dto';

@Injectable()
export class PermissionService {
  constructor(private dataSource: DataSource) {}

  // 查找用户接口权限集
  async findUserApis(userId: string): Promise<RouteDto[]> {
    const permsResult = await this.dataSource
      .createQueryBuilder()
      .select(['pa.apiUrl', 'pa.apiMethod'])
      .from('user_role', 'ur')
      .leftJoin('role_permission', 'rp', 'ur.role_id = rp.role_id')
      .leftJoin('permission_api', 'pa', 'rp.permission_id = pa.permission_id')
      .where('ur.user_id = :userId', { userId })
      .groupBy('pa.apiUrl')
      .addGroupBy('pa.apiMethod')
      .getRawMany();
    const perms = permsResult.map((item) => ({
      path: item.pa_apiUrl,
      method: item.pa_apiMethod,
    }));
    return perms;
  }

  create(createPermissionDto: CreatePermissionDto) {
    return 'This action adds a new permission';
  }

  findAll() {
    return `This action returns all permission`;
  }

  findOne(id: number) {
    return `This action returns a #${id} permission`;
  }

  update(id: number, updatePermissionDto: UpdatePermissionDto) {
    return `This action updates a #${id} permission`;
  }

  remove(id: number) {
    return `This action removes a #${id} permission`;
  }
}
